package cn.edu.nju.ws.sview.wyge.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import org.apache.commons.collections.comparators.ComparableComparator;

public class SubjectComparator implements Comparator<String>{
	public static void main(String[] args){
		String o1 = "scrollu10849191";
		String o2 = "scrollu109";
		String o3 = "scrollu1412";
		String o4 = "b10851336_3";
		String o5 = "b10851336_15";
		String o6 = "b10851336:25";
		ArrayList<String> list = new ArrayList<String>();
		list.add(o2);
		list.add(o4);
		list.add(o6);
		list.add(o3);
		list.add(o5);
		list.add(o1);
		System.out.println(list.toString());
		Collections.sort(list, new SubjectComparator());
		System.out.println("after:"+list.toString());
	}
	/**
	 * blank node is listed after than(greater than) uri
	 * uris compared by their id (the greater, listed the latter)
	 * blanknodes compared by their doc num , then inner id (the greater, listed the latter)
	 */
	@Override
	public int compare(String o1, String o2) {
		int cmp = 0;
//		System.out.println("o1:"+o1+"|"+o1.matches("\\w*[u]\\d+")+"|"+o1.matches("\\w*[b]\\d+[:|_]\\d+"));
//		System.out.println("o2:"+o2+"|"+o2.matches("\\w*[u]\\d+")+"|"+o2.matches("\\w*[b]\\d+[:|_]\\d+"));
		if(o1.matches("\\w*[u]\\d+") && o2.matches("\\w*[u]\\d+")){//"\\w*[u|b]\\d+"
			int no1 = Integer.valueOf(o1.substring(o1.lastIndexOf("u")+1));
			int no2 = Integer.valueOf(o2.substring(o2.lastIndexOf("u")+1));
			cmp = no1-no2;
//			System.out.println(no1+"|"+no2+"|"+cmp);
		}else if(o1.matches("\\w*[b]\\d+[:|_]\\d+") && o2.matches("\\w*[b]\\d+[:|_]\\d+")){
			int starto1 = o1.lastIndexOf("b")+1;
			int middleo1 = o1.lastIndexOf(":");
			middleo1 = middleo1>0?middleo1:o1.lastIndexOf("_");
			int starto2 = o2.lastIndexOf("b")+1;
			int middleo2 = o2.lastIndexOf(":");
			middleo2 = middleo2>0?middleo2:o2.lastIndexOf("_");
			int doco1 = Integer.valueOf(o1.substring(starto1, middleo1));
			int doco2 = Integer.valueOf(o2.substring(starto2, middleo2));
			cmp = doco1 - doco2;
//			System.out.println("docs:"+doco1+"|"+doco2+"|"+cmp);
			if(cmp == 0){
				int ido1 = Integer.valueOf(o1.substring(middleo1+1));
				int ido2 = Integer.valueOf(o2.substring(middleo2+1));
				cmp = ido1 - ido2;
//				System.out.println("docs:"+ido1+"|"+ido2+"|"+cmp);
			}
		}else if(o1.matches("\\w*[b]\\d+[:|_]\\d+")){
			cmp = 1;
		}else if(o2.matches("\\w*[b]\\d+[:|_]\\d+")){
			cmp = -1;
		}else{
			System.out.println("Illegal: "+o1+"|"+o2);
			cmp = o1.compareTo(o2);
		}
//		System.out.println("cmpresult:"+o1+"|"+o2+"|"+cmp+"\n");
		return cmp;
	}

	

}
